package logic

import (
	"context"
	"errors"
	"video/model/cache"
	"video/model/mysql"
	"video/pkg"

	"video/videorpc/internal/svc"
	"video/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordUpdateLogic {
	return &PasswordUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 密码重置
func (l *PasswordUpdateLogic) PasswordUpdate(in *videorpc.PasswordUpdateRequest) (*videorpc.PasswordUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User
	err := findUser.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if findUser.ID == 0 {
		return nil, errors.New("该手机号未注册，请前往注册")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result == "" {
		return nil, errors.New("当前未发送短信验证码")
	}
	if result != in.SendSms {
		return nil, errors.New("当前短信验证码错误，请重新输入")
	}

	if in.NewPassword != in.ReNewPassword {
		return nil, errors.New("新密码与确认密码不一致，请重新输入")
	}
	if findUser.Password == pkg.Md5Str(in.NewPassword) {
		return nil, errors.New("新密码与原密码一致，请重新输入")
	}

	findUser.Password = pkg.Md5Str(in.NewPassword)
	err = findUser.PasswordUpdate(mysql.DB)
	if err != nil {
		return nil, errors.New("密码重置失败，请联系管理员")
	}

	return &videorpc.PasswordUpdateResponse{
		UserId: int64(findUser.ID),
	}, nil
}
